package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.minio.service.FileOpsService;
import com.atguigu.tingshu.common.minio.service.impl.FileOpsServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnProperty(prefix = "minio",name = "enable",havingValue = "true")
@EnableConfigurationProperties(MinioProperties.class)
//@Configuration
public class MinioAutoConfiguration {
    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {
        MinioClient minioClient =
                MinioClient.builder()
                        // minio服务器的地址在哪里
                        .endpoint(minioProperties.getEndpointUrl())
                        .credentials(minioProperties.getAccessKey(),//账户
                                minioProperties.getSecreKey())  //密码
                        .build();

        // 2.minio是否存在一个桶

        try {
            boolean found = minioClient.bucketExists
                    (BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());
            if (!found) {
                //不存在桶创建
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build());
                //设置访问桶的公共权限
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(minioProperties.getPolicyJson())
                        .build());
            } else {
                System.out.println(minioProperties.getBucketName() + " exists");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("minio对象初始化失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }

    }
    @Bean
    public FileOpsService fileOpsService() {
        return new FileOpsServiceImpl();
    }
}
